package com.module.home.ui.home

import android.content.Context
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.asLiveData
import androidx.lifecycle.viewModelScope
import com.common.app.data.bean.home.AllScoringModel
import com.common.app.data.bean.home.HomeMainCardModel
import com.common.base.app.viewmodel.BaseViewModel
import com.common.base.data.CommonBean
import com.common.app.data.repository.HomeApi
import com.common.app.utls.SseManager
import com.common.app.widget.floatingView.SFloatingView
import com.common.base.app.extras.loadRound
import com.common.base.app.viewmodel.Cancel
import com.common.base.data.ListCommon
import com.module.home.data.bean.UploadResult
import com.module.ble.db.table.UserBloodOxygen
import com.module.ble.db.table.UserBodyTemperature
import com.module.ble.db.table.UserHeartRate
import com.module.ble.repo.BloodOxygenRepo
import com.module.ble.repo.BodyTemperatureRepo
import com.module.ble.repo.HeartRateRepo
import com.module.home.R
import com.module.home.data.HomeSubApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import me.yokeyword.fragmentation.SupportFragment

/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2022/10/12
 * <p>
 * 描述：直播首页
 * <p>
 * 修订历史：
 */
class HomeMainViewModel : BaseViewModel() {

    val allHeartRates: LiveData<List<UserHeartRate>>? =
        HeartRateRepo.instance.findAllFlow()?.asLiveData()

    val allBloodOxygens: LiveData<List<UserBloodOxygen>>? =
        BloodOxygenRepo.instance.findAllFlow()?.asLiveData()

    val allUserBodyTemperatures: LiveData<List<UserBodyTemperature>>? =
        BodyTemperatureRepo.instance.findAllFlow()?.asLiveData()

    var mDeviceConnectionFirst = true//首次连接

    var scoreColor1 = 0f
    var scoreColor2 =0f
    var scoreColor3 = 0f
    var scoreColor4 = 0f

    val mBodyBalanceScore = MutableLiveData<Int>()
    val mPressureScore = MutableLiveData<Int>()
    val mSleepScore = MutableLiveData<Int>()
    val mExerciseScore = MutableLiveData<Int>()
    val mSignsScore = MutableLiveData<Int>()

    private val homeFloatView = MutableLiveData<SFloatingView?>()
    val floatingViewClick = MutableLiveData<Any>()

    private val sseManager = SseManager()
//    private val sseManager = SseManager(staTime = "1755604984000")
    val _sseData = MutableLiveData<String>()

    init {

        mBodyBalanceScore.value = 0
        mPressureScore.value = 0
        mSleepScore.value = 0
        mExerciseScore.value = 0
        mSignsScore.value = 0

        // 在IO线程监听SSE事件，在Main线程更新UI
        viewModelScope.launch {
            sseManager.sseEvents
                // SSE处理在IO线程
                .collect { event ->
                    // collect在Main线程执行，可以安全更新UI
                    when (event) {
                        is SseManager.SseEvent.Data -> {
                            _sseData.value = event.content
                        }
                        is SseManager.SseEvent.Error -> {
                            Log.e("SSE", "Error: ${event.message}")
                        }
                        is SseManager.SseEvent.Connected -> {
                            Log.d("SSE", "Connected")
                        }
                        is SseManager.SseEvent.Disconnected -> {
                            Log.d("SSE", "Disconnected")
                        }
                    }
                }
        }
    }

    override fun onCleared() {
        super.onCleared()
        sseManager.stopSseConnection()
    }

    fun startSse() {
        sseManager.startSseConnection(viewModelScope)
    }

    /**
     * 重新连接SSE
     */
    fun reconnectSse() {
        sseManager.stopSseConnection()
        sseManager.startSseConnection(viewModelScope)
    }

    /**
     * 带延迟的重连（避免频繁重连）
     */
    fun reconnectSseWithDelay(delayMs: Long = 1000) {
        viewModelScope.launch {
            sseManager.stopSseConnection()
            delay(delayMs)
            sseManager.startSseConnection(viewModelScope)
        }
    }

    fun stopSse() {
        sseManager.stopSseConnection()
    }

    fun refreshDBAllData() {
        HeartRateRepo.instance.refreshData()
        BloodOxygenRepo.instance.refreshData()
        BodyTemperatureRepo.instance.refreshData()
    }


    fun initFloatWindow(
        context: Context?,
        mType: Int? = 0,
        mUrl: String? = "",
        mFra: SupportFragment
    ) {

        context?.apply {
            if (homeFloatView.value == null) {
                homeFloatView.value = SFloatingView(this) {
                    //点击
                    floatingViewClick.postValue("")
                }
            }

            homeFloatView.value?.setRightEdgeVerticalDragOnly(true)// 开启右边缘限制拖拽模式
//            homeFloatView.value?.getImgView()?.loadRound(R.drawable.home_float_view_icon,100)
            homeFloatView.value?.getImgView()?.setImageDrawable(getDrawable(R.drawable.home_float_view_icon))
        }
    }

    fun showFloatWindow() {
        homeFloatView.value?.showWindow()

    }

    fun hideFloatWindow() {

        homeFloatView.value?.hideWindow()

    }

    fun uploadHrData(upList:List<Any>?,startDataTime: String,endDataTime: String,dataType: String,dataSize: String,  firmwareVersion: String, macAddress: String, manufacturerId: String, base64EnData: String): LiveData<CommonBean<UploadResult>> = emit({}){
        val response = HomeSubApi.uploadCompressedData(startDataTime,endDataTime,dataType,dataSize,firmwareVersion,macAddress,manufacturerId,base64EnData)
        // 创建包含原始数据的响应
        CommonBean<UploadResult>().apply {
            Code = response.Code
            Data = UploadResult(upList, response.Data)
        }
    }


    fun getHomeAiNotifDetail(error: Cancel): LiveData<ListCommon<HomeMainCardModel>> = emit(error) {
        HomeApi.getHomeAiNotifDetail()
    }

    fun getAllScoringFactors( date :String,error: Cancel): LiveData<CommonBean<AllScoringModel>> = emit(error) {
        HomeApi.getAllScoringFactors(date)
    }

    fun uploadSyncFinished(error: Cancel): LiveData<CommonBean<Any>> = emit(error) {
        HomeSubApi.uploadSyncFinished()
    }
}